<?php
//error_reporting(-1);
class MainController extends MemberController {

    public function actionSwitch() {
        if (isset($_POST['switch'])) {
            if ($_POST['switch_id'] != '') {
                $data = sys_network::model()->with('rel_network_to_member')->find('network_mid=:mid', array(':mid' => $_POST['switch_id']));
                if ($data != false) {
                    Yii::app()->user->setState('network_id', $data->network_id);
                    Yii::app()->user->setState('network_mid', $data->network_mid);
                    Yii::app()->user->setState('network_sponsor_network_id', $data->network_sponsor_network_id);
                    Yii::app()->user->setState('network_upline_network_id', $data->network_upline_network_id);
                    Yii::app()->user->setState('member_name', $data->rel_network_to_member->member_name);
                    Yii::app()->user->setState('member_nickname', $data->rel_network_to_member->member_nickname);
                    Yii::app()->user->setState('member_join_datetime', $data->rel_network_to_member->member_join_datetime);
                    Yii::app()->user->setState('member_serial_id', $data->rel_network_to_member->member_serial_id);
                    Yii::app()->user->setState('member_image', ($data->rel_network_to_member->member_image) ? $data->rel_network_to_member->member_image : '_default.jpg');
                    Yii::app()->user->setState('member_last_login', $data->rel_network_to_member->member_last_login);

                    $this->redirect('dashboard');
                }
            }
        }
    }
     
    protected function _date_diff_manual($date1, $date2, $restrict_one_day = false){
        
        
        $day_of_1 = date_format(date_create($date1), 'd');
        $day_of_2 = date_format(date_create($date2), 'd');
        
        $month_of_1 = date_format(date_create($date1), 'm');
        $month_of_2 = date_format(date_create($date2), 'm');
        
        $status = false;
        if($restrict_one_day == true) {
            if($day_of_2 > $day_of_1 AND $month_of_2 == $month_of_1){
                $status = true;
            } else if(($day_of_2 > $day_of_1 OR $day_of_2 < $day_of_1) AND $month_of_2 !== $month_of_1){
                $status = true;
            }
        } else {
            if($day_of_2 >= $day_of_1 AND $month_of_2 == $month_of_1){
                $status = true;
            } else if(($day_of_2 >= $day_of_1 OR $day_of_2 <= $day_of_1) AND $month_of_2 !== $month_of_1){
                $status = true;
            }
        }
        
        return $status;
    }
    
    

    public function actionInformation()
    {
        
        try{
            $model = site_page::model()->findByPk(42);
        }
        catch (CDbException $e)
        {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        $this->render(
                'information',
                array(
                    'model'=>$model,
                ));
    }
    
    public function actionSertifikat($output=''){
        $type_member = function_lib::get_type_member(Yii::app()->user->getState('network_id'));
        if(strtoupper($type_member) != "WHUM"){
            $this->redirect(array('profile'));
        }
        $sql = "SELECT serial_products_user_datetime FROM sys_serial_products_user WHERE serial_products_user_network_id = '".Yii::app()->user->getState('network_id')."' AND serial_products_user_serial_products_id like 'WHUM%' limit 1";
        $date_upgrade = Yii::app()->db->createCommand($sql)->queryScalar();
        
        $mid = Yii::app()->user->getState('network_mid');
        $nama = Yii::app()->user->getState('member_name');
        $date_join = Yii::app()->user->getState('member_join_datetime');
        $explode_date = explode(" ", $date_upgrade);
        $date_format = $explode_date[0];
        $explode_date = explode("-", $date_format);
        $date = $explode_date[2];
        $month = $explode_date[1];
        $year = $explode_date[0];
        
        switch($output)
        {
        	case 'fpdf':
        	$saveDir=dirname(__FILE__).'/../../../../assets/sertifikat/';
        	require_once dirname(__FILE__).'/../../../extensions/fpdf/fpdf.php';
        	
			$pdf = new FPDF();
			$pdf->AddPage('L','A4');
			
			$pdf->Image(dirname(__FILE__).'/../../../../images/bg-certificate-600.jpg',12,25,270);
			
			$pdf->SetFont('Arial','B',7.5);
			$pdf->Text(235,70,$mid);
			
			$pdf->SetFont('Arial','B',16);
			$pdf->Text(122,97,$nama);
			
			
			$pdf->SetFont('Arial','B',14);
			$pdf->Text(145,120,$date );
			
			
			$pdf->SetFont('Arial','B',14);
			$pdf->Text(157,120,$month );
			
			
			$pdf->SetFont('Arial','B',14);
			$pdf->Text(175,120,substr($year,-2) );
			
			//$pdf->Output($saveDir.'sert_'.$mid.'.pdf','F');
			$pdf->Output('sert_'.$mid.'.pdf','D');
        	break;
        
        	case 'html':
        	     $this->renderPartial(
                'sertifikat_html',
                array(
                    'mid'=>$mid,
                    'nama'=>$nama,
                    'tanggal'=>$date,
                    'bulan' => $month,
                    'tahun'=>substr($year,-2),
                ));
       		break;
       		default:
       		$this->render(
                'sertifikat',
                array(
                    'mid'=>$mid,
                    'nama'=>$nama,
                    'tanggal'=>$date,
                    'bulan' => $month,
                    'tahun'=>substr($year,-2),
                ));
       		break; 	
        }
        
        
    }
    
    public function actionSertifikat_whqd($output=''){
        
        $type_member = function_lib::get_type_member(Yii::app()->user->getState('network_id'));
        if(strtoupper($type_member) != "WHQD"){
            $this->redirect(array('profile'));
        }
        
        $sql = "SELECT serial_products_user_datetime FROM sys_serial_products_user WHERE serial_products_user_network_id = '".Yii::app()->user->getState('network_id')."' AND serial_products_user_serial_products_id like 'WHUM%' limit 1";
        $date_upgrade = Yii::app()->db->createCommand($sql)->queryScalar();
        
        $mid = Yii::app()->user->getState('network_mid');
        $nama = Yii::app()->user->getState('member_name');
        $date_join = Yii::app()->user->getState('member_join_datetime');
        $explode_date = explode(" ", $date_upgrade);
        $date_format = $explode_date[0];
        $explode_date = explode("-", $date_format);
        $date = $explode_date[2];
        $month = $explode_date[1];
        $year = $explode_date[0];
        
        switch($output)
        {
        	case 'fpdf':
        	$saveDir=dirname(__FILE__).'/../../../../assets/sertifikat/';
        	require_once dirname(__FILE__).'/../../../extensions/fpdf/fpdf.php';
        	
			$pdf = new FPDF();
			$pdf->AddPage('L','A4');
			
			$pdf->Image(dirname(__FILE__).'/../../../../images/bg-certificate-600-whqd.jpg',12,25,270);
			
			$pdf->SetFont('Arial','B',7.5);
			$pdf->Text(235,70,$mid);
			
			$pdf->SetFont('Arial','B',16);
			$pdf->Text(122,97,$nama);
			
			
			$pdf->SetFont('Arial','B',14);
			$pdf->Text(145,120,$date );
			
			
			$pdf->SetFont('Arial','B',14);
			$pdf->Text(157,120,$month );
			
			
			$pdf->SetFont('Arial','B',14);
			$pdf->Text(175,120,substr($year,-2) );
			
			//$pdf->Output($saveDir.'sert_'.$mid.'.pdf','F');
			$pdf->Output('sert_'.$mid.'.pdf','D');
        	break;
        
        	case 'html':
        	     $this->renderPartial(
                'sertifikat_html_whqd',
                array(
                    'mid'=>$mid,
                    'nama'=>$nama,
                    'tanggal'=>$date,
                    'bulan' => $month,
                    'tahun'=>substr($year,-2),
                ));
       		break;
       		default:
       		$this->render(
                'sertifikat_whqd',
                array(
                    'mid'=>$mid,
                    'nama'=>$nama,
                    'tanggal'=>$date,
                    'bulan' => $month,
                    'tahun'=>substr($year,-2),
                ));
       		break; 	
        }
        
        
    }


    public function actionDashboard() {
        $this->render('dashboard');
    }

    public function actionProfile() {
        if (isset($_SESSION['pin_validation']) && ($_SESSION['pin_validation'] == true)) {
            $model = sys_member::model()->findByPk(Yii::app()->user->getId());
            $old_filename = $model->member_image;

            if (isset($_POST['sys_member'])) {
                $pin_validation = vo_network::pin_validation(Yii::app()->user->getId(), $_POST['pin']);
                if ($pin_validation) {

                    $model->attributes = $_POST['sys_member'];
                    $model->member_last_update = date("Y-m-d H:i:s");
                    $model->member_is_updated_by_member = '1';

                    //file upload
                    $file = CUploadedFile::getInstance($model, 'member_image');
                    $filename = '';
                    if ((is_object($file) && get_class($file) === 'CUploadedFile')) {
                        $filename = function_lib::url_title($file->name);
                        $model->member_image = CUploadedFile::getInstance($model, 'member_image');
                        $model->member_image = $filename;
                    }

                    //simpan ke data member 1 grup
                    $arr_network_group = vo_network::get_network_group(Yii::app()->user->getId());
                    $transaction = Yii::app()->db->beginTransaction();
                    try {
                        //vo_network::update_group_profile(Yii::app()->user->getId(), $model);
                        function_lib::update_with_relation("sys_member, sys_network", "member_network_id", $model, "network_id = member_network_id AND network_group_network_id = '" . Yii::app()->user->getId() . "'");
                        $transaction->commit();

                        if (is_object($file)) {
                            $model->member_image = CUploadedFile::getInstance($model, 'member_image');
                            if ($model->member_image->saveAs(Yii::app()->params['config']['updir']['member'] . $filename)) {
                                Yii::app()->user->setState('member_image', $filename);
                                if ($old_filename != '' && file_exists(Yii::app()->params['config']['updir']['member'] . $old_filename)) {
                                    unlink(Yii::app()->params['config']['updir']['member'] . $old_filename);
                                }
                            }
                        }
                        Yii::app()->user->setFlash('success', 'Proses Ubah Data berhasil diproses.');
                        $_SESSION['pin_validation'] = false;
                    } catch (CDbException $e) {
                        $transaction->rollback();
                        Yii::app()->user->setFlash('error', 'Proses Ubah Data gagal diproses.');
                    }
                } else {
                    Yii::app()->user->setFlash('error', 'Maaf, PIN yang anda masukkan belum benar.');
                }

                $this->redirect(array('profile'));
            }

            $this->render('profile', array(
                'model' => $model,
            ));
        } else {
            $_SESSION['pin_validation'] = false;
            $model = new captcha_form;

            if (isset($_POST['captcha_form'])) {
                $model->attributes = $_POST['captcha_form'];

                $pin_validation = vo_network::pin_validation(Yii::app()->user->getId(), $_POST['pin']);
                if (!$pin_validation) {
                    Yii::app()->user->setFlash('error', 'Maaf, PIN yang anda masukkan belum benar.');
                    Yii::app()->controller->redirect(array('/member/main/profile'));
                } elseif (!$model->validate()) {
                    Yii::app()->user->setFlash('error', 'Maaf, Kode Unik yang anda masukkan belum benar.');
                    Yii::app()->controller->redirect(array('/member/main/profile'));
                } else {
                    $_SESSION['pin_validation'] = true;
                    Yii::app()->controller->redirect(array('/member/main/profile'));
                }
            } else {
                $this->render('pin_validation', array(
                    'model' => $model,
                ));
            }
        }
    }

    public function actionPassword() {

        if (isset($_POST['edit'])) {
            $pin_validation = vo_network::pin_validation(Yii::app()->user->getId(), $_POST['pin']);
            $password_validation = vo_network::password_validation(Yii::app()->user->getId(), $_POST['old_password']);
            if ($pin_validation) {
                if ($password_validation) {
                    if ($_POST['new_password'] === $_POST['confirm_password']) {
                        $transaction = Yii::app()->db->beginTransaction();
                        try {
                            $sql = "UPDATE sys_password, sys_network 
                                SET password_value = MD5('" . $_POST['new_password'] . "') 
                                WHERE network_id = password_network_id AND network_group_network_id = '" . Yii::app()->user->getId() . "'";
                            Yii::app()->db->createCommand($sql)->execute();
                            $transaction->commit();

                            Yii::app()->user->setFlash('success', 'Proses Ubah Password berhasil diproses.');
                        } catch (CDbException $e) {
                            $transaction->rollback();
                            Yii::app()->user->setFlash('error', 'Proses Ubah Data gagal diproses.');
                        }
                    } else {
                        Yii::app()->user->setFlash('error', 'Maaf, Kedua Password yang anda masukkan tidak sama.');
                    }
                } else {
                    Yii::app()->user->setFlash('error', 'Maaf, Password Lama yang anda masukkan belum benar.');
                }
            } else {
                Yii::app()->user->setFlash('error', 'Maaf, PIN yang anda masukkan belum benar.');
            }
            $this->redirect(array('password'));
        }

        $this->render('password');
    }

    public function actionTestimony() {

        if (isset($_POST['save'])) {
            $pin_validation = vo_network::pin_validation(Yii::app()->user->getId(), $_POST['pin']);
            if ($pin_validation) {
                if (trim($_POST['testimony_content']) != '') {
                    $new_order_by = function_lib::get_new_order_by("sys_member_testimony", "member_testimony_order_by");
                    $sql = "INSERT INTO sys_member_testimony SET 
                        member_testimony_network_id = '" . Yii::app()->user->getState('network_id') . "', 
                        member_testimony_content = '" . trim($_POST['testimony_content']) . "', 
                        member_testimony_input_datetime = '" . date("Y-m-d H:i:s") . "', 
                        member_testimony_is_approve = '0', 
                        member_testimony_order_by = '" . $new_order_by . "', 
                        member_testimony_home_is_active = '0'";
                    Yii::app()->db->createCommand($sql)->execute();

                    Yii::app()->user->setFlash('success', 'Proses Kirim Testimoni berhasil disimpan. Terima kasih.');
                } else {
                    Yii::app()->user->setFlash('error', 'Maaf, Isi Testimoni belum anda isi.');
                }
            } else {
                Yii::app()->user->setFlash('error', 'Maaf, PIN yang anda masukkan belum benar.');
            }
            $this->redirect(array('testimony'));
        }

        $this->render('testimony');
    }

}
